
#include "xdns-address-query.h"
#include "xdns-data.h"
#include "xdns-encoder.h"
#include "xdns-protocol.h"
#include "xdns-question-info.h"
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <sstream>

using namespace std;

XdnsAddressQuery::XdnsAddressQuery(const struct in_addr* ipAddress,
                                   XdnsListener* listener)
: XdnsQuery(XQT_IpAddress, listener),
  m_ipAddress()
{
    assert(ipAddress != NULL);
    memcpy(&m_ipAddress, ipAddress, sizeof(struct in_addr));
}

XdnsAddressQuery::~XdnsAddressQuery()
{
}

const struct in_addr*
XdnsAddressQuery::GetAddress() const
{
    return (&m_ipAddress);
}

XdnsError
XdnsAddressQuery::ComposeQueryData(unsigned short requestId,
                                   XdnsData& data
                                   ) const
{
    string name = GenerateQuestionName();
    return XdnsEncoder::GenerateData(requestId,
                                     XDNS_TYPE_PTR,
                                     XDNS_CLASS_IN,
                                     name,
                                     data);
}

void
XdnsAddressQuery::GetQuestion(XdnsQuestionInfo& question) const
{
    question.m_qtype = XDNS_TYPE_PTR;
    question.m_qclass = XDNS_CLASS_IN;
    question.m_qname = GenerateQuestionName();
}

string
XdnsAddressQuery::GenerateQuestionName() const
{
    unsigned long address = ntohl(static_cast<unsigned long>(m_ipAddress.s_addr));
    unsigned long part1 = ((address >> 24) & 0xff);
    unsigned long part2 = ((address >> 16) & 0xff);
    unsigned long part3 = ((address >> 8) & 0xff);
    unsigned long part4 = (address & 0xff);
    stringstream ss;
    ss<<part4<<"."<<part3<<"."<<part2<<"."<<part1;
    string name(ss.str());
    name += ".in-addr.arpa";

    return name;
}

